from datetime import datetime
from app import db

class Payment(db.Model):
    """支付模型"""
    __tablename__ = 'payments'
    
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('orders.id'), nullable=False, index=True)
    payment_no = db.Column(db.String(64), unique=True, index=True, nullable=False, comment='支付流水号')
    transaction_id = db.Column(db.String(64), unique=True, index=True, comment='微信支付订单号')
    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='支付金额')
    payment_method = db.Column(db.String(20), default='wechat', comment='支付方式')
    status = db.Column(db.SmallInteger, default=0, index=True, comment='支付状态: 0未支付 1支付成功 2支付失败 3已退款')
    paid_at = db.Column(db.DateTime, comment='支付时间')
    refund_at = db.Column(db.DateTime, comment='退款时间')
    refund_amount = db.Column(db.Numeric(10, 2), comment='退款金额')
    refund_reason = db.Column(db.String(255), comment='退款原因')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    order = db.relationship('Order', backref='payments')
    logs = db.relationship('PaymentLog', backref='payment', lazy='dynamic')
    
    def __repr__(self):
        return f'<Payment {self.id}: {self.payment_no}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        status_map = {0: '未支付', 1: '支付成功', 2: '支付失败', 3: '已退款'}
        
        def format_datetime(dt):
            """安全格式化时间"""
            if not dt:
                return None
            if hasattr(dt, 'strftime'):
                return dt.strftime('%Y-%m-%d %H:%M:%S')
            return str(dt)
        
        return {
            'id': self.id,
            'order_id': self.order_id,
            'payment_no': self.payment_no,
            'transaction_id': self.transaction_id,
            'amount': float(self.amount),
            'payment_method': self.payment_method,
            'status': self.status,
            'status_text': status_map.get(self.status, '未知'),
            'paid_at': format_datetime(self.paid_at),
            'refund_at': format_datetime(self.refund_at),
            'refund_amount': float(self.refund_amount) if self.refund_amount else None,
            'refund_reason': self.refund_reason,
            'created_at': format_datetime(self.created_at)
        }


class PaymentLog(db.Model):
    """支付日志模型"""
    __tablename__ = 'payment_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    payment_id = db.Column(db.Integer, db.ForeignKey('payments.id'), nullable=False, index=True)
    action = db.Column(db.String(50), nullable=False, comment='操作类型')
    status = db.Column(db.SmallInteger, comment='操作状态')
    request_data = db.Column(db.Text, comment='请求数据')
    response_data = db.Column(db.Text, comment='响应数据')
    error_message = db.Column(db.Text, comment='错误信息')
    ip_address = db.Column(db.String(45), comment='IP地址')
    user_agent = db.Column(db.String(500), comment='用户代理')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    
    def __repr__(self):
        return f'<PaymentLog {self.id}: {self.action}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'payment_id': self.payment_id,
            'action': self.action,
            'status': self.status,
            'request_data': self.request_data,
            'response_data': self.response_data,
            'error_message': self.error_message,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at and hasattr(self.created_at, 'strftime') else str(self.created_at) if self.created_at else None
        }